import os
import multiprocessing as mp
import sys
from time import sleep

from typing import List
# ip列表二维数组，内部嵌套ip列表一维数组
ip_lists = []
# ip列表一维数组
ip_list = [0, 0, 0, 0]
# 总共多少次，创建多少个文件
total_num = 256
# 应用内核数量，启动多少进程
multi = 16
# 总共次数，不能被内核数整除时，程序被迫退出
if total_num%multi != 0:
    print('内核不能正常分配')
    sys.exit(1)
# 应需轮回执行多少次=总次数/内核数
cycles_num=total_num//multi
# print(f'应需轮回执行{cycles_num}次')

files = []
os.makedirs('文件夹0', exist_ok=True)
for i in range(total_num):
    # 初始化
    file = open(f'文件夹0/file{i}.txt', 'a',encoding='utf-8')
    files.append(file)
    ip_lists.append(ip_list)


def generate_data(str_s, i):
    str_s[0] = f'{i}.'
    for k in range(256):
        str_s[1] = f'{k}.'
        for j in range(256):
            str_s[2] = f'{j}.'
            for m in range(256):
                str_s[3] = f'{m}'
                # print(''.join(str_s))
                # print(sys.getdefaultencoding())
                text=(''.join(str_s))
                files[i].write(str(text + '\n'))
    files[i].flush()
    files[i].close()


process_list = []
for index_i in range(total_num):
    process_list.append(mp.Process(target=generate_data, args=(ip_lists[index_i], index_i)))
    # generate_data(ip_lists[index_i],index_i)



if __name__=='__main__' :
    # print(process_list)
    process_list_temp=[]
    while cycles_num:
        for process in range(multi):
            p=process_list.pop(0)
            p.start()
            process_list_temp.append(p)
            sleep(1)

            # process_list[process].start()
        for process in range(multi):
            process_list_temp.pop(0).join()
            # process.join()
            sleep(1)
        cycles_num -= 1
